package test.service.analysis;

import org.apache.commons.math3.distribution.TDistribution;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;

/**
 * 
 * @Description Spearman 相关性验证
 *
 * @author liuqinghua
 * @date 2023-9-13
 */
public class Spearman {
    private double[] x;

    private double[] y;
    SpearmansCorrelation p = new SpearmansCorrelation();

    public Spearman(double[] x, double[] y) {
        this.x = x;
        this.y = y;
    }

    public double getR() {
        return p.correlation(x, y);
    }

    public double getTValue() {
        double up = x.length - 2;
        double r = getR();
        double down = 1 - (r * r);
        return r * Math.sqrt(up / down);
    }

    /***
     * 
     * @param flag:true=双侧 false=单侧
     * @return
     */
    public double getPValue(boolean flag) {
        TDistribution td = new TDistribution(x.length - 2);
        double t = getTValue();
        double cumulative = td.cumulativeProbability(t);
        double p = t > 0 ? 1 - cumulative : cumulative;
        return flag ? p * 2 : p;
    }

    public double getPValue() {
        return getPValue(true);
    }

    public static void main(String[] args) {
        double[] d1 = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        double[] d2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        Spearman sp = new Spearman(d1, d2);
        System.out.println("相关系数r：" + sp.getR());
        System.out.println("p值：" + sp.getPValue());
    }

}
